package com.central.apps.util;

import cn.hutool.core.util.StrUtil;
import com.central.app.common.convert.CfgMapConvert;
import com.central.app.model.BizObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import java.util.*;

public class AppCommonExtUtil {

    /**
     * 设置查询条件
     *
     * @param object
     * @param sql
     * @param params
     * @return
     * @throws Exception
     */
    public static StringBuilder setFindParams(BizObject object, String sql, Map<String, Object> params, List<String> tableColumns) throws Exception {
        //添加自定义条件
        String converWhereCondition = CfgMapConvert.converWhereCondition(params);
        //过滤日期from条件
        Map<String, Object> dateFrom = CfgMapConvert.converWhereDateFrom(params);
        //过滤日期to条件
        Map<String, Object> dateTo = CfgMapConvert.converWhereDateTo(params);
        //过滤is null查询条件
        Set<String> isNull = CfgMapConvert.converWhereIsNull(params);
        //过滤is not null查询条件
        Set<String> isNotNull = CfgMapConvert.converWhereIsNotNull(params);

        //过滤排序信息
        Map<String, Object> orders = CfgMapConvert.converOrders(params);
        //添加自定义排序
        String customOrder = CfgMapConvert.converCusOrder(params);

        //添加or条件
        Map<String, Object> ors = CfgMapConvert.converOrs(params);

        String whereMultiQuery = "";
        Map<String, List<Object>> whereIns = new HashMap<>();
        Map<String, List<Object>> whereNotIns = new HashMap<>();
        Map<String, Object> whereEqs = new HashMap<>();
        Map<String, Object> whereLikes = new HashMap<>();
        if (object != null) {
            //多字段模糊匹配查询（多字段or+like查询数据）
            whereMultiQuery = CfgMapConvert.converMultiQuery(object, params);
            //过滤in查询条件
            whereIns = CfgMapConvert.converWhereIns(object,params);
            //过滤not in查询条件
            whereNotIns = CfgMapConvert.converWhereNotIns(object,params);
            //过滤where查询条件
            whereEqs = CfgMapConvert.converWhereEqs(object, params);
            //like条件
            whereLikes = CfgMapConvert.converWhereLikes(object, params);
        }

        if (CollectionUtils.isNotEmpty(tableColumns)) {
            convertWhereLikes(whereLikes, tableColumns, params);
        }

        StringBuilder sqlSb = new StringBuilder();
        if (StringUtils.isNotEmpty(sql)) {
            sqlSb.append(sql);
            if (!sql.contains("where") && !sql.contains("WHERE")) {
                sqlSb.append(" where 1 = 1 ");
            }
        }

        //设置自定义条件
        sqlSb.append(converWhereCondition);

        // 设置like查询条件
        if (whereLikes != null && !whereLikes.isEmpty()) {
            for (Map.Entry<String, Object> entry : whereLikes.entrySet()) {
                if (StringUtils.isNotEmpty(entry.getKey())) {
                    sqlSb.append(" and ").append(entry.getKey()).append(" like ").append("'%").append(entry.getValue()).append("%'");
                }
            }
        }

        // 设置where查询条件
        if (whereEqs != null && !whereEqs.isEmpty()) {
            for (Map.Entry<String, Object> entry : whereEqs.entrySet()) {
                if (StringUtils.isNotEmpty(entry.getKey())) {
                    sqlSb.append(" and ").append(entry.getKey()).append(" = ").append(entry.getValue());
                }
            }
        }

        //设置where in查询条件
        if (whereIns != null && !whereIns.isEmpty()) {
            for (Map.Entry<String, List<Object>> entry : whereIns.entrySet()) {
                if (StringUtils.isNotEmpty(entry.getKey())) {
                    sqlSb.append(" and ").append(entry.getKey()).append(" in (");
                    List<Object> list = entry.getValue();
                    for (Object obj : list) {
                        sqlSb.append(obj.toString());
                    }
                    sqlSb.append(")");
                }
            }
        }

        //设置where not in查询条件
        if (whereNotIns != null && !whereNotIns.isEmpty()) {
            for (Map.Entry<String, List<Object>> entry : whereNotIns.entrySet()) {
                if (StringUtils.isNotEmpty(entry.getKey())) {
                    sqlSb.append(" and ").append(entry.getKey()).append(" in (");
                    List<Object> list = entry.getValue();
                    for (Object obj : list) {
                        sqlSb.append(obj.toString());
                    }
                    sqlSb.append(")");
                }
            }
        }

        // 设置where datefrom查询条件
        if (dateFrom != null && !dateFrom.isEmpty()) {
            for (Map.Entry<String, Object> entry : dateFrom.entrySet()) {
                if (StringUtils.isNotEmpty(entry.getKey())) {
                    sqlSb.append(" and ").append(entry.getKey()).append(" >= ").append(entry.getValue());
                }
            }
        }

        // 设置where dateto查询条件
        if (dateTo != null && !dateTo.isEmpty()) {
            for (Map.Entry<String, Object> entry : dateTo.entrySet()) {
                if (StringUtils.isNotEmpty(entry.getKey())) {
                    sqlSb.append(" and ").append(entry.getKey()).append(" <= ").append(entry.getValue());
                }
            }
        }

        //设置where is null查询条件
        if (isNull != null && !isNull.isEmpty()) {
            for (String val : isNull) {
                sqlSb.append(" and (").append(val).append(" is null or ").append(val).append(" = ''").append(")");
            }
        }

        //设置where is null查询条件
        if (isNotNull != null && !isNotNull.isEmpty()) {
            for (String val : isNotNull) {
                sqlSb.append(" and (").append(val).append(" is not null or ").append(val).append(" != ''").append(")");
            }
        }

        //设置or条件
        if (ors != null && !ors.isEmpty()) {
            sqlSb.append("(");
            for (Map.Entry<String, Object> entry : ors.entrySet()) {
                if (StringUtils.isNotEmpty(entry.getKey())) {
                    sqlSb.append(" or ").append(entry.getKey()).append(" = ").append(entry.getValue());
                }
            }
            sqlSb.append(")");
        }

        //设置多字段模糊匹配查询条件
        if (StringUtils.isNotEmpty(whereMultiQuery)) {
            sqlSb.append(" and (").append(whereMultiQuery).append(")");
        }

        //设置自定义排序
        if (StringUtils.isNotEmpty(customOrder)) {
            sqlSb.append(" order by ").append(customOrder);
        } else {
            //设置排序条件
            if (orders != null && !orders.isEmpty()) {
                sqlSb.append(" order by ");
                for (Map.Entry<String, Object> entry : orders.entrySet()) {
                    if (StringUtils.isNotEmpty(entry.getKey())) {
                        sqlSb.append(" ").append(entry.getKey()).append(" ").append(entry.getValue()).append(",");
                    }
                }

                sqlSb.deleteCharAt(sqlSb.length() - 1);
            } else {
                sqlSb.append(" order by createtime desc");
            }
        }

        return sqlSb;
    }

    /**
     * 根据表字段转换like条件
     *
     * @param whereLikes
     * @param tableColumns
     * @param querys
     * @return
     */
    public static void convertWhereLikes(Map<String, Object> whereLikes, List<String> tableColumns, Map<String, Object> querys) {
        List<String> filterKeys = new ArrayList();
        filterKeys.add("limit".toUpperCase(Locale.ROOT));
        filterKeys.add("page".toUpperCase(Locale.ROOT));
        filterKeys.add("access_token".toUpperCase(Locale.ROOT));
        filterKeys.add("dsf".toUpperCase(Locale.ROOT));
        filterKeys.add("_orders".toUpperCase(Locale.ROOT));
        filterKeys.add("_wheres".toUpperCase(Locale.ROOT));
        filterKeys.add("_where_in".toUpperCase(Locale.ROOT));
        filterKeys.add("_where_not_in".toUpperCase(Locale.ROOT));
        filterKeys.add("_where_date_from".toUpperCase(Locale.ROOT));
        filterKeys.add("_where_date_to".toUpperCase(Locale.ROOT));
        filterKeys.add("_where_is_null".toUpperCase(Locale.ROOT));
        filterKeys.add("_where_is_notnull".toUpperCase(Locale.ROOT));
        filterKeys.add("_where_relation".toUpperCase(Locale.ROOT));
        filterKeys.add("where_condition".toUpperCase(Locale.ROOT));
        filterKeys.add("where_childs".toUpperCase(Locale.ROOT));
        filterKeys.add("order_condition".toUpperCase(Locale.ROOT));
        Iterator var6 = querys.entrySet().iterator();

        while(true) {
            Object value;
            String whereKey;
            while(true) {
                String key;
                boolean flag;
                String lowerKey;
                do {
                    do {
                        do {
                            if (!var6.hasNext()) {
                                return;
                            }

                            Map.Entry<String, Object> entry = (Map.Entry)var6.next();
                            key = (String)entry.getKey();
                            value = entry.getValue();
                        } while(key == null);
                    } while(key.equals(""));

                    flag = false;
                    Iterator var11 = filterKeys.iterator();

                    while(var11.hasNext()) {
                        lowerKey = (String)var11.next();
                        if (key.toUpperCase(Locale.ROOT).contains(lowerKey)) {
                            flag = true;
                            break;
                        }
                    }
                } while(flag);

                whereKey = StrUtil.trimStart(key);
                whereKey = StrUtil.trimEnd(whereKey);
                lowerKey = whereKey.toLowerCase();
                if (lowerKey.endsWith("_where_like")) {
                    whereKey = whereKey.replace("_where_like", "").replace("_where_like".toUpperCase(), "").trim();
                }

                if (((List) tableColumns).contains(lowerKey)) {
                    whereKey = "t." + lowerKey;
                    break;
                }
            }

            whereLikes.put(whereKey, value);
        }
    }
}
